package com.zzf.concurrent.example.design.pattern.observer.thread.example;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.stream.IntStream;

/**
 * 使用观察者设计模式来监听线程状态
 * @author GaoFeng2017
 * @date 2019/9/6 14:03
 */
@Slf4j
public class App {
    public static void main(String[] args) {
        LifeCycleListener lifeCycleListener = new LifeCycleListener();
        IntStream.rangeClosed(1, 4).forEach(index -> new Thread(new AbstractRunnableObserver(lifeCycleListener) {

            @Override
            public void run() {
                Thread currentThread = Thread.currentThread();
                try {
                    updateStatus(currentThread, ThreadStatus.RUNNING, null);
                    TimeUtil.sleep(1000);
                    if (index % 2 == 0) {
                        int i = 1 / 0;
                    }
                    updateStatus(currentThread, ThreadStatus.TERMINATED, null);
                } catch(Exception e) {
                    updateStatus(currentThread, ThreadStatus.ERROR, e);
                }
            }

        }, "thread-" + index).start());
    }
}
